package com.lin.util;

import com.lin.enums.util.ResponseStatusCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * Http连接工具
 * 
 * @author com.lin, 2019-12-21
 */
@Slf4j
public class HttpUrlConnectionUtil {

    private static String encode = "UTF-8";
    private static String content_type = "application/json;charset=UTF-8";

    /**
     * 发送Get请求
     *
     * @param urlStr url地址
     * @return 返回的信息
     * @author com.lin, 2019-12-21
     */
    public static String doGet(String urlStr) {
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
//            SSLSocketFactory ssl = HttpUrlConnectionUtil.getSsl();
//            https请求需要
//            connection.setSSLSocketFactory(ssl);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", content_type);
            connection.setUseCaches(false);
            connection.connect();

            // 回调的结果
            int responseCode = connection.getResponseCode();
            // 结果
            String result;
            if (responseCode != ResponseStatusCode.OK.getCode()) {
                result = IOUtils.toString(connection.getErrorStream());
            } else {
                result = IOUtils.toString(connection.getInputStream());
            }
            return result;
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return null;
    }

    /**
     * 发送Post请求
     *
     * @param urlStr  url地址
     * @param content 发送的信息
     * @return 返回的信息
     * @author com.lin, 2019-12-21
     */
    public static String doPost(String urlStr, String content) {
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
//            SSLSocketFactory ssl = HttpUrlConnectionUtil.getSsl();
//            https请求需要
//            connection.setSSLSocketFactory(ssl);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", content_type);
            connection.setUseCaches(false);
            connection.connect();

            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(content.getBytes(encode));
            out.flush();
            out.close();

            int responseCode = connection.getResponseCode();
            String result;
            if (responseCode != ResponseStatusCode.OK.getCode()) {
                result = IOUtils.toString(connection.getErrorStream());
            } else {
                result = IOUtils.toString(connection.getInputStream());
            }
            return result;
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return null;
    }

    /**
     * SSL工具，传输Https信息
     *
     * @return ssl对象
     * @throws NoSuchProviderException  异常
     * @throws NoSuchAlgorithmException 异常
     * @throws KeyManagementException   异常
     * @author com.lin, 2019-12-21
     */
	private static SSLSocketFactory getSsl() throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustManager = new TrustManager[]{};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, trustManager, new java.security.SecureRandom());
        return sslContext.getSocketFactory();
    }


}
